package cn.xo68.boot.auth.server.token.impl;

import cn.xo68.boot.auth.server.domain.LoginFailLimit;
import cn.xo68.boot.auth.server.domain.OauthUser;
import cn.xo68.boot.auth.server.properties.AuthServerProperties;
import cn.xo68.boot.auth.server.service.LoginFailLimitService;
import cn.xo68.boot.auth.server.token.AbstractTokenRequestCheck;
import cn.xo68.core.date.DateTime;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 密码模式的令牌请求审核
 * @author wuxie
 * @date 2018-8-10
 */
@Component
public class TokenRequestCheckOnPassword extends AbstractTokenRequestCheck {

    private static final Logger logger= LoggerFactory.getLogger(TokenRequestCheckOnPassword.class);

    @Autowired
    private AuthServerProperties authServerProperties;
    @Autowired
    private LoginFailLimitService loginFailLimitService;

    @Override
    public OauthUser checkCredentials() throws OAuthProblemException {
        LoginFailLimit loginFailLimit=loginFailLimitService.get(this.getOAuthTokenRequest().getUsername());
        if(loginFailLimit.getFailTimes()>= authServerProperties.getLoginFailMaxTimes()){
            throw OAuthProblemException.error("登录失败","登录失败次数过多");
        }
        OauthUser oauthUser =getOauthUserService().getByAccount(this.getOAuthTokenRequest().getUsername());
        if(oauthUser ==null || !oauthUser.getUserPass().equals(this.getOAuthTokenRequest().getPassword())){
            loginFailLimit.setLastDate(DateTime.Now().getDate());
            loginFailLimit.setFailTimes(loginFailLimit.getFailTimes()+1);
            loginFailLimitService.put(loginFailLimit);
            throw OAuthProblemException.error("登录失败","用户名或密码错误");
        }
        if(loginFailLimit.getFailTimes()>0){
            loginFailLimitService.delete(this.getOAuthTokenRequest().getUsername());
        }
        return oauthUser;
    }

}
